package com.itfreer.http.request;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.itfreer.utils.JSONUtils;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * 定义可以带map参数的json对象post方法
 */
public class JsonStringArrayPostRequest extends Request<List<String>> {

    private Map<String,String> mMap;
    private Response.Listener<List<String>> mListener;

    public JsonStringArrayPostRequest(String url,
                                      Response.Listener<List<String>> listener,
                                      Response.ErrorListener errorListener,Map map) {
        super(Request.Method.POST, url, errorListener);
        mListener=listener;
        mMap=map;
    }
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mMap;
    }

    @Override
    protected Response<List<String>> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            List<String> result = JSONUtils.toBean(jsonString, List.class);
            return Response.success(result,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (Exception je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(List<String> response) {
        mListener.onResponse(response);
    }
}
